import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col, Tooltip, message } from 'antd'
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'


import {
  getHospitalListRequest,  //获取医院分页列表请求
  getProvinceListRequest,  //获取省
  getCityOrBlockRequest,   //获取市或区请求
  checkedStatusRequest,    //切换状态请求
} from "@api/hospital/hospitalList"

import type {
  getHosListReqContentType,    //返回值中数组的类型
  getHosListSearchParamsType,  //参数中params的类型
  hospitalListItemsType,       //返回值中数组的每一项的类型
  getProvinceListReqReturn,    //获取省的请求返回值类型
} from "@api/hospital/model/hospitalListType"



export default function HospitalList() {
  //创建表单实例
  const [from] = Form.useForm()

  //编程式路由导航
  const navigate = useNavigate()

  //定义状态加载表格时loading
  const [isloading, setIsloading] = useState(false)
  //定义状态保存当前页 改变重新渲染页面
  const [page, setPage] = useState(1)
  //定义状态保存每页条数 改变重新渲染页面
  const [limit, setLimit] = useState(10)
  //定义状态保存总数据条数初始为0 请求数据回来之后实时改动
  const [total, setTotal] = useState(0)

  //定义状态保存初始数组 请求到数据后 改变数组渲染页面
  const [hospitalList, setHospitalList] = useState<getHosListReqContentType>([])
  //定义状态保存查询时用户输入的内容 改变重新渲染页面
  const [searchParams, setSeachParams] = useState<getHosListSearchParamsType>({})
  //定义状态保存省的数据
  const [province, setProvince] = useState<getProvinceListReqReturn>([])
  //定义状态保存市的数据
  const [city, setCity] = useState<getProvinceListReqReturn>([])
  //定义状态保存区的数据
  const [block, setBlock] = useState<getProvinceListReqReturn>([])
  //定义状态保存类型的数据
  const [style, setStyle] = useState<getProvinceListReqReturn>([])
  //定义状态上下线成功后查询渲染
  const [checkedCear , setCheckedClear] = useState(true)


  //1.初始化的时候发送请求渲染页面
  useEffect(() => {
    (async () => {
      //发送请求开始加载动画
      setIsloading(true)

      //发送请求
      const re = await getHospitalListRequest(page, limit, searchParams)

      //渲染页面
      setHospitalList(re.content)
      //显示总数据
      setTotal(re.totalElements)

      //请求接收停止加载动画
      setIsloading(false)
    })()
  }, [page, limit, searchParams , checkedCear])


  //2.初始化请求省的数据
  useEffect(() => {
    (async () => {
      const result = await getProvinceListRequest();

      //请求回来的省的数据保存在状态中
      setProvince(result);

    })()
  }, [])


  //3.初始化请求类型
  useEffect(() => {
    (async() => {
      const result = await getCityOrBlockRequest("10000");

      //请求回来的类型的数据保存在状态中
      setStyle(result);

    })()
  }, [])


  //表格列的配置描述
  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      align: "center" as "center", //文本居中
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },

    {
      title: '医院logo',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return <img width={100} src={`data:image/jpeg;base64,${data.logoData}`} alt="" />
      }
    },

    {
      title: '医院名称',
      align: "center" as "center", //文本居中
      dataIndex: "hosname"
    },

    {
      title: '等级',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString
      }
    },

    {
      title: '详细地址',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },

    {
      title: '状态',
      align: "center" as "center", //文本居中
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? "下线" : "上线"
      }
    },

    {
      title: '创建时间',
      align: "center" as "center", //文本居中
      dataIndex: "createTime"
    },

    {
      title: '操作',
      align: "center" as "center", //文本居中

      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any , data:hospitalListItemsType) {
        //拿到当前数据的id
        const {id} = data;
        //拿到读取数据的status
        const {status} = data
        //拿到当前数据的hoscode
        const {hoscode} = data

        return (
          <div>
            <Tooltip title={"查看"}>
              <Button type='primary' onClick = {goHospitalMessage(id)}>查看</Button>
            </Tooltip>

            <Tooltip title={"排班"}>
              <Button type='primary' onClick = {goHospitalSchedule(hoscode)}>排班</Button>
            </Tooltip>

            <Tooltip title={status === 0 ? "上线" : "下线"}>
              <Button type='primary' onClick = {checkStatusHandle(id , status === 0 ? 1 : 0)}>{
                status === 0 ? "上线" : "下线"
              }</Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];


  //4.改变页码的回调函数
  const changePageHandle = (page: number, limit: number) => {
    //改变状态查询发送请求渲染页码
    setPage(page)
    setLimit(limit)
  }

  //5.点击省获取对应的市的回调函数
  const getCityList = async (id: string) => {
    const result = await getCityOrBlockRequest(id);

    //请求回来的市的数据保存在状态中
    setCity(result)

    //再次点击省要清空市和区的输入内容
    from.setFieldsValue({ cityCode: "", districtCode: "" })

    //并且要清除区的数据
    setBlock([])

  }

  //6.点击省获取对应的市的回调函数
  const getBlockList = async (id: string) => {
    const result = await getCityOrBlockRequest(id);

    //请求回来的市的数据保存在状态中
    setBlock(result)

    //再次点击清除区的输入内容
    from.setFieldsValue({ districtCode: "" })

  }

  //7.点击查询的回调函数
  const searchHosListHandle = (finishValue:getHosListSearchParamsType) => {
    //收集表单数据改变状态发送请求查询
    setSeachParams(finishValue)
  }

  //8.点击清除的回调函数
  const clearSearchHandle = () => {
    //查询设置searchParams状态为空 则会重新发送请求渲染
    setSeachParams({})
  }

  //9.点击查看的回调函数
  const goHospitalMessage = (id:string) => {
    return () => {
      navigate(`/syt/hospatil/hospatildetail/${id}`)
    }
  }

  //10.点击上下线的回调函数
  const checkStatusHandle = (id:string , status: 0 | 1) => {
    return async () => {
      await checkedStatusRequest(id , status);

      //提示
      if(status === 0){
        message.success("下线成功")
      }else{
        message.success("上线成功")
      }

      //重新渲染
      setCheckedClear(!checkedCear)

    }
  }

  //11.点击排班的回调函数
  const goHospitalSchedule = (hoscode:string) => {
    return () => {
      navigate(`/syt/hospatil/hospatilschedule/${hoscode}`)
    }
  }



  return (
    <div>
      <Card>

        <Form
          name="basic"
          form={from} //创建表单实例
          onFinish={searchHosListHandle}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={getCityList} //点击省的回调
                >
                  {
                    province.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={getBlockList} //点击市的回调
                >
                  {
                    city.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {
                    block.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    style.map((item) => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="default" htmlType="reset" onClick = {clearSearchHandle}>
                  清空
                </Button>
              </Form.Item>
            </Col>

          </Row>

        </Form>


        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"

          //表格加载动画
          loading={isloading}

          //分页器
          pagination={{
            //页码的配置：当前页码
            current: page,
            //每页条数
            pageSize: limit,
            // 总数据的数量
            total,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            //展示数据总数
            showTotal(total) {
              return `数据总是是${total}条`
            },

            //点击页码的回调
            onChange: changePageHandle,

          }}
        />

      </Card>
    </div >
  )
}
